package com.oitsm.mo.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.oitsm.commons.action.BaseAction;
import com.oitsm.mo.cache.NodeCache;
import com.oitsm.mo.entity.Node;
import com.oitsm.mo.service.MOService;
import com.oitsm.utils.JSONUtils;

/**
 * 节点 Action
 * @author Arab Runner
 * Jun 25, 2011 12:46:08 PM
 */
@SuppressWarnings("serial")
public class NodeAction extends BaseAction {
	@Autowired
	private MOService moService;
	
	public void setMoService(MOService moService) {
		this.moService = moService;
	}
	
	/**
	 * 添加节点
	 * @return
	 * @throws Exception
	 */
	public String addGroupNode()throws Exception{
		HttpServletRequest request = this.getRequest();
		String name = request.getParameter("name");
		Long parentId = null;
		try{
			parentId = Long.parseLong(request.getParameter("parent"));
		}catch(Exception e){}
		
		Node n = new Node();
		n.setParentId(parentId);
		n.setName(name);
		n.setType(Node.TYPE_GROUP);
		
		moService.addNode(n);
		
		JSONObject jo = new JSONObject();
		jo.put("success", true);
		JSONObject nodeJo = JSONObject.fromObject(n);
		jo.put("node", nodeJo);
		
		JSONUtils.write(this.getResponse(), jo.toString());
		
		return null;
	}
	
	/**
	 * 删除节点
	 * @return
	 * @throws Exception
	 */
	public String deleteNodes()throws Exception{
		String[] ids = this.getRequest().getParameterValues("ids");
		List<Long> idList = new ArrayList<Long>();
		for(String id : ids){
			idList.add(Long.parseLong(id));
		}
		moService.deleteNodes(idList);
		JSONUtils.writeSuccessJSON(this.getResponse());
		return null;
	}
	
	/**
	 * update 节点
	 * @return
	 * @throws Exception
	 */
	public String updateNode()throws Exception{
		HttpServletRequest request = this.getRequest();
		Long id = Long.getLong(request.getParameter("id"));
		String name = request.getParameter("name");
		Node n = NodeCache.getNode(id);
		n.setName(name);
		moService.updateNode(n);
		JSONUtils.writeSuccessJSON(this.getResponse());
		return null;
	}
}
